package persist

import (
	"log"
	"gopkg.in/olivere/elastic.v5"
	"context"
)

const URL = "http://192.168.14.221:9200"

func ItemSaver() chan interface{} {
	out := make(chan interface{})
	go func() {
		// save
		itemCount := 0
		for {
			item := <-out
			log.Printf("Item Saver: go item "+"#%d %v", itemCount, item)
			itemCount++

			//log.Printf("%s", item)
			_, err := save(item)
			if err != nil {
				log.Printf("Item Saver: error "+"saving item %v: %v", item, err)
			}
		}
	}()
	return out
}

func save(item interface{}) (id string, err error) {
	client, err := elastic.NewClient(
		// must turn off sniff in docker
		elastic.SetURL(URL),
		elastic.SetSniff(false),
	)
	if err != nil {
		return "", err
	}

	res, err := client.Index().
		Index("dating_profile").
		Type("zhenai").
		BodyJson(item).
		Do(context.Background())
	if err != nil {
		return "", err
	}
	//log.Printf("%#v\n", res)
	return res.Id, nil
}
